package LeetCode;

import java.util.ArrayList;
import java.util.Stack;

public class LC_144_BinaryTreePreorderTraversal {

    public static void main(String[] args) {

    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class Solution {
        public ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<>();
            if (root != null) {
                result.add(root.val);
                result.addAll(preorderTraversal(root.left));
                result.addAll(preorderTraversal(root.right));
            }
            return result;
        }
    }

    static class Solution_2 {
        public ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<>();
            if (root == null) return result;
            Stack<TreeNode> nodeStack = new Stack<>();
            nodeStack.push(root);

            while (!nodeStack.empty()) {
                TreeNode node = nodeStack.pop();
                result.add(node.val);
                if (node.right != null) nodeStack.push(node.right);
                if (node.left != null) nodeStack.push(node.left);
            }

            return result;
        }
    }

}